const meetingRoomDao = require('../database/MeetingRoomDao');
const authMiddleware = require('../middleware/AuthMiddleWare');
const { success, fail } = require('../utils/response');

const onlineUsers = require('../utils/onlineUsers').getOnlineUsers();
const { getIo } = require('../socket');

const router = require('express').Router();

// 获取所有会议室列表（公开接口）
router.get('/list', async (req, res) => {
  try {
    const rooms = await meetingRoomDao.getAllRooms();
    res.json(success(rooms));
  } catch (error) {
    res.status(500).json(fail(5000, '获取会议室列表失败'));
  }
});

// 获取指定会议室详情（公开接口）
router.get('/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const room = await meetingRoomDao.getRoomById(id);

    if (room) {
      res.json(success(room));
    } else {
      res.status(404).json(fail(4000, '会议室不存在'));
    }
  } catch (error) {
    res.status(500).json(fail(5000, '获取会议室信息失败'));
  }
});

// 添加新会议室（管理员权限）
router.post('/add', authMiddleware.isAdmin, async (req, res) => {
  try {
    const roomId = await meetingRoomDao.addMeetingRoom(req.body);
    res.status(201).json(success({ message: '会议室添加成功', roomId }));
  } catch (error) {
    res.status(500).json(fail(5000, '添加会议室失败'));
  }
});

// 更新会议室状态（员工权限）
router.put('/:id/status', authMiddleware.isEmployee, async (req, res) => {
  try {
    const { status } = req.body;
    const result = await meetingRoomDao.updateRoomStatus(req.params.id, status);
    if (result) {
      const io = getIo();
      io.emit('server:room-status-updated', {
        roomId: req.params.id,
        status
      });
      return res.json(success({ message: '会议室状态更新成功' }));
    } else {
      res.status(404).json(fail(4001, '会议室不存在'));
    }
  } catch (error) {
    res.status(500).json(fail(5000, '更新会议室状态失败'));
  }
});

// 删除会议室（管理员权限）
router.delete('/:id', authMiddleware.isAdmin, async (req, res) => {
  try {
    const id = req.params.id;
    const result = await meetingRoomDao.deleteMeetingRoom(id);

    if (result) {
      const io = getIo();
      io.emit('server:room-deleted', {
        roomId: id,
        message: '会议室已被删除'
      });
      res.json(success({ message: '会议室删除成功' }));
    } else {
      res.status(404).json(fail(4000, '会议室不存在'));
    }
  } catch (error) {
    res.status(500).json(fail(5000, '删除会议室失败'));
  }
});

module.exports = router;